package qiniu.voidcepc.voicepc.demos.web.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import qiniu.voidcepc.voicepc.demos.web.server.VoiceServer;
import qiniu.voidcepc.voicepc.demos.web.utils.MultipartFileResampler;
import qiniu.voidcepc.voicepc.demos.web.utils.WavReSample;
import qiniu.voidcepc.voicepc.demos.web.vo.ApiResponse;

import javax.sound.sampled.UnsupportedAudioFileException;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@RestController
@RequestMapping("/voidupload")
public class VoiceController {

    @Autowired
    VoiceServer voiceServer;


    /**
     * 指定本地文件，进行采样率的转换
     * */
    @GetMapping("/test001")
    public ApiResponse<String> testVoice() throws UnsupportedAudioFileException, IOException {
        String res = voiceServer.localVoice();
        WavReSample.reSampleRate(8000,"D:\\QiNiu2\\VoicePC\\src\\main\\resources\\localVoice\\MYVOICE1.wav","D:\\QiNiu2\\VoicePC\\src\\main\\resources\\localVoice\\MYVOICE2.wav");
        return ApiResponse.ok(res);
    }

    @PostMapping("/audio")
    public ApiResponse<?> handleAudioUpload(
            @RequestParam("audio") MultipartFile file,
            @RequestParam(value = "userId", required = false) String userId) {
        if (file.isEmpty()) {
            return ApiResponse.error("上传文件请不要为空","ZN");
        }
        if(!file.getOriginalFilename().endsWith("wav")) {
            return ApiResponse.error("上传文件类型需要要为wav","ZN");
        }
        String res = voiceServer.origianlVoid(file,16000);
        return ApiResponse.ok(res );
    }

    /**
     * 通过前端的语音命令去执行操作
     *
     * 进行语音指令操作的使用的唯一的接口，其他的接口都是进行测试的接口
     * */
    @PostMapping("/audioTask")
    public ApiResponse<?> handleAudioTask(
            @RequestParam("audio") MultipartFile file) {
        if (file.isEmpty()) {
            return ApiResponse.error("上传文件请不要为空","ZN");
        }
        if(!file.getOriginalFilename().endsWith("wav")) {
            return ApiResponse.error("上传文件类型需要要为wav","ZN");
        }
        String res = voiceServer.origianlVoiceTask(file,16000);

        return ApiResponse.ok(res);
    }
    
    /**
     * 上传音频文件，自动调整采样率并下载转换后的文件
     * 支持实时采样率转换和文件下载
     */
    @PostMapping("/resample")
    public void resampleVoice(@RequestParam(value = "file") MultipartFile file,
                            @RequestParam(value = "targetSampleRate", required = false, defaultValue = "8000") int targetSampleRate,
                            HttpServletResponse response) throws IOException {
        if (file.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().write("上传文件为空");
            return;
        }
        
        try {
            // 检测原始文件采样率
            int originalSampleRate = MultipartFileResampler.getSampleRate(file);
            System.out.println("原始文件采样率: " + originalSampleRate + "Hz，目标采样率: " + targetSampleRate + "Hz");
            
            // 设置响应头
            String originalFilename = file.getOriginalFilename();
            String filename = originalFilename != null && originalFilename.contains(".") 
                ? originalFilename.substring(0, originalFilename.lastIndexOf('.')) 
                : originalFilename;
            String outputFilename = filename + "_" + targetSampleRate + ".wav";
            
            response.setContentType("audio/wav");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + outputFilename + "\"");
            
            // 执行采样率转换并写入响应流
            try (InputStream resampledStream = MultipartFileResampler.resampleMultipartFileToStream(file, targetSampleRate);
                 OutputStream out = response.getOutputStream()) {
                
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = resampledStream.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
                out.flush();
            }
            
        } catch (UnsupportedAudioFileException e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().write("不支持的音频格式: " + e.getMessage());
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("采样率转换失败: " + e.getMessage());
        }
    }
}
